/*
 * Copyright (c) 2015. For Intelligent Group.
 */

package com.intelligent.ispc.common.utils;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by julia on 16/8/9.
 */
public class DateUtils {

    /**
     * Format string to date.
     *
     * @param date   date
     * @param format format string
     * @return Date
     */
    public static Date string2Date(String date, String format) {
        Date dateResult = null;

        try {
            if (StringUtils.isSpecialBlank(date)) {
                dateResult = null;
            } else {
                if (date.split(":").length == 1) {
                    dateResult = null;
                } else {
                    if (date.split(":").length == 2 && date.endsWith(":")) {
                        date = date + "00";
                    } else if (date.split(":").length == 2 && !date.endsWith(":")) {
                        date = date + ":00";
                    }
                }

                dateResult = DateTime.parse(date, DateTimeFormat.forPattern(format)).toDate();
            }
        } catch (Exception e) {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            sdf.setLenient(false);

            SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);

            try {
                dateResult = DateTime.parse(sdf.format(sdf1.parse(date)), DateTimeFormat.forPattern(format)).toDate();
            } catch (ParseException ex) {
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                sdf2.setLenient(false);

                try {
                    dateResult = DateTime.parse(sdf.format(sdf2.parse(date)), DateTimeFormat.forPattern(format)).toDate();
                } catch (ParseException exx) {
                    SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy/MM/dd/HH:mm:ss");
                    sdf3.setLenient(false);

                    try {
                        dateResult = DateTime.parse(sdf.format(sdf3.parse(date)), DateTimeFormat.forPattern(format)).toDate();
                    } catch (ParseException exxx) {
                        exxx.printStackTrace();
                        return null;
                    }
                }
            }
        }

        return dateResult;
    }
}
